package com.dmz.oauth2.token.granter;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import com.dmz.oauth2.token.authentication.TokenAuthenticationToken;
import com.dmz.oauth2.utils.JwtUtils;
import com.dmz.oauth2.utils.RandomUtils;


public class RicoTokenGranter extends AbstractTokenGranter{
	
	 private final AuthenticationManager authenticationManager;
	/**
     * 账号密码登录
     */
    private static final String GRANT_TYPE = "implicit_token";

    public RicoTokenGranter(AuthenticationManager authenticationManager,
            AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
    		this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
    }
	
	private RicoTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
	             ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
		super(tokenServices, clientDetailsService, requestFactory, grantType);
		this.authenticationManager = authenticationManager;
	}
	
	@Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
        String mobile = parameters.get("phone");
        String code = parameters.get("code");
        //调用自定义的token扩展 实现用户认证 
        Authentication userAuth = new TokenAuthenticationToken(mobile,code);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        try {
            userAuth = authenticationManager.authenticate(userAuth);
        }
        catch (AccountStatusException ase) {
            //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
            throw new InvalidGrantException(ase.getMessage());
        }
        catch (BadCredentialsException e) {
            // If the username/password are wrong the spec says we should send 400/invalid grant
            throw new InvalidGrantException(e.getMessage());
        }
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate mobile: " + mobile);
        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
	protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) {
		 String jti = UUID.randomUUID().toString();
		 
		// 登录token有效时间
	    Calendar nowTime = Calendar.getInstance();
	    Integer accessTokenValiditySeconds = client.getAccessTokenValiditySeconds();
	    nowTime.add(Calendar.SECOND, accessTokenValiditySeconds);
	    Date expireDate = nowTime.getTime();
	    
	    
	    // token密钥
        String secret = UUID.randomUUID().toString()+RandomUtils.getCode(16);
        Map<String, Object> map = new HashMap<>(3);
        map.put(JwtUtils.TOKEN_JWT_OPENID, UUID.randomUUID());
        map.put(JwtUtils.TOKEN_JWT_JTI, jti);
        map.put(JwtUtils.TOKEN_JWT_CLIENT_ID, client.getClientId());
        // 生成token
        String token = JwtUtils.createToken(map, expireDate, secret);
		DefaultOAuth2AccessToken accessToken=new DefaultOAuth2AccessToken(token);
		return accessToken;
	}

}
